package com.chunxiadong.controller;

import com.chunxiadong.entity.Picture;
import com.chunxiadong.utils.CreateUUID;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;

/**
 * @auther QiuShangcheng
 * @create 2021/6/8
 */
@Controller
public class UtilController {
    private Logger log = Logger.getLogger(this.getClass());

    /**
     * 上传图片
     *
     * @param file
     * @param req
     * @return
     */
    @RequestMapping("/admin/util/uploadImg")
    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest req, HttpSession session) {
        try {
            String path = req.getServletContext().getRealPath("/cache");
            log.info("PictureAddr：" + path);
            if (!file.isEmpty()) {
                File rootFile = new File(path);
                if (!rootFile.exists()) {
                    rootFile.mkdirs();
                }
                String img_name = CreateUUID.create() + ".jpg";
                File file2 = new File(rootFile, img_name);
                file.transferTo(file2);
                session.setAttribute("pictureAddr", "http://www.chunxiadong.top/cache/" + img_name);
            } else {
                session.setAttribute("pictureAddr", "No Picture Upload!");
            }
            return "redirect:/admin/picture/input";
        } catch (Exception e) {
            session.setAttribute("pictureAddr", "Upload Picture Case Error!");
            log.error(file.toString() + "Upload Picture Case Error!");
            return "redirect:/admin/picture/input";
        }
    }


}
